<template>
	<view class="page">

		<view class="banner">
			<u--image :src="model1.event.image1" width="750rpx" height="260rpx"></u--image>
		</view>
		<view class="avatar-btn">
			<u-button @tap="upload" text="上传封面"></u-button>
		</view>
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<view class="form">
			<u--form labelPosition="top" :required="true" :model="model1" :labelStyle="{width: '300rpx'}" :rules="rules"
				ref="uForm">
				<u-form-item label="活动主题" prop="event.theme" :required="true" borderBottom ref="item1">
					<u--input v-model="model1.event.theme" border="none" placeholder="请输入活动主题"></u--input>
				</u-form-item>
				<!-- 			<u-form-item label="价格" prop="event.price" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.price" border="none"></u--input>
				</u-form-item> -->
				<u-form-item v-if="member && member.super_leader == '是'" label="Leader" :required="true"
					prop="event.price" borderBottom @click="leader_show = true" ref="item1">
					<u--input v-model="model1.event.leader" disabled disabledColor="#ffffff" placeholder="请选择局长"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="价格" :required="true" prop="event.price" borderBottom 
					ref="item1">
					<u--input type="number" clearable v-model="model1.event.price" border="none"></u--input>
					<!-- @click="price_show = true" -->
<!-- 					<u--input v-model="model1.event.price" disabled disabledColor="#ffffff" placeholder="请选择价格"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon> -->
				</u-form-item>
				<u-form-item label="最少组局女性" :required="true" prop="event.female_member" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.female_member" border="none"></u--input>
				</u-form-item>
				<u-form-item label="最少成局人数" :required="true" prop="event.min_member" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.min_member" border="none"></u--input>
				</u-form-item>
				<u-form-item label="最大成局人数" :required="true" prop="event.sum_member" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.sum_member" border="none"></u--input>
				</u-form-item>

				<u-form-item label="活动标签" :required="true" prop="tagList" borderBottom ref="item1">
					<u-checkbox-group v-model="model1.tagList" shape="square">
						<view style="display: flex;flex-wrap: wrap;">
							<u-checkbox :customStyle="{margin: '5px'}" v-for="(item, index) in checkTagList"
								:key="index" :label="item.name" :name="item.name" :checked="item.checked">
							</u-checkbox>
						</view>
					</u-checkbox-group>
				</u-form-item>
				
				
				<u-form-item label="团体限定" prop="grouptagList" borderBottom ref="item1">
					<u-checkbox-group v-model="model1.grouptagList" shape="square">
						<view style="display: flex;flex-wrap: wrap;">
							<u-checkbox :customStyle="{margin: '5px'}" v-for="(item, index) in group_list"
								:key="index" :label="item.name" :name="item.nid" :checked="item.checked">
							</u-checkbox>
						</view>
					</u-checkbox-group>
				</u-form-item>
				
				
				
		 
				<u-form-item label="活动提供" :required="true" borderBottom ref="item2">
					<radio-group @change="status_provide">
						<radio class="mr-20" 
						v-for="(item, index) in provider_list" 
						:key="index" 
						:value="item.value"
						:checked="item.checked"
						:disabled="item.disabled">
						{{item.name}}
						</radio>
					</radio-group>
				</u-form-item>
				
				
				<u-form-item label="联系电话" prop="event.phone" :required="true" borderBottom ref="item1">
					<u--input type="number"  v-model="model1.event.phone" border="none"></u--input>
				</u-form-item>
				

				<!-- 				<u-form-item label="首页推荐" :required="true" borderBottom ref="item2">
					<radio-group @change="recommendChange" v-model="model1.event.recommend">
						<radio class="mr-20" v-for="(item, index) in recommendList" :key="index" :name="item.value"
							:checked="item.checked">{{item.name}}
						</radio>
					</radio-group>
				</u-form-item> -->

				<u-form-item label="状态" :required="true" borderBottom ref="item2">
					<radio-group @change="statusChange">
						<radio class="mr-20" 
						v-for="(item, index) in statusList" 
						:key="index" 
						:value="item.value"
						:checked="item.checked">{{item.name}}
						</radio>
					</radio-group>
				</u-form-item>
				

				<u-form-item label="活动状态" :required="true" borderBottom ref="item2">
					<radio-group @change="eventStatusChange">
						<radio class="mr-20" v-for="(item, index) in eventStatusList" :key="index" :value="item.value"
							:checked="item.checked">{{item.name}}
						</radio>
					</radio-group>
				</u-form-item>

				<!-- 				<u-form-item label="简介" :required="true" prop="remark" borderBottom ref="item3">
					<u--textarea placeholder="不低于3个字" v-model="model1.event.remark" count></u--textarea>
				</u-form-item> -->

				<u-form-item label="报名开始" :required="true" prop="event.apply_starttime" borderBottom
					@click="showDatetimePicker(1)" ref="item1">
					<u--input v-model="model1.event.apply_starttime" disabled disabledColor="#ffffff"
						placeholder="请选择报名开始" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="报名结束" :required="true" prop="event.apply_endtime" borderBottom
					@click="showDatetimePicker(2)" ref="item1">
					<u--input v-model="model1.event.apply_endtime" disabled disabledColor="#ffffff"
						placeholder="请选择报名结束" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="活动开始" :required="true" prop="event.starttime" borderBottom
					@click="showDatetimePicker(3)" ref="item1">
					<u--input v-model="model1.event.starttime" disabled disabledColor="#ffffff" placeholder="请选择活动开始"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="活动结束" :required="true" prop="event.endtime" borderBottom
					@click="showDatetimePicker(4)" ref="item1">
					<u--input v-model="model1.event.endtime" disabled disabledColor="#ffffff" placeholder="请选择活动结束"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="活动地址" :required="true" prop="event.address" labelWidth="70">
					<u-input placeholder="点击选择地址" v-model="model1.event.address" @focus="chooseLocation"
						suffixIcon="map-fill" suffixIconStyle="color: #909399">
					</u-input>
				</u-form-item>

				<u-form-item label="活动详情" ref="item1">
					<EditorContext name="content" :html="model1.event.content" @changes="detail_content">
					</EditorContext>
				</u-form-item>

				<!-- 				<u-form-item label="活动结束后详情" ref="item1">
					<EditorContext name="finnsh_content" :html="model1.event.finnsh_content" @changes="detail_content">
					</EditorContext>
				</u-form-item> -->

				<u-form-item label="用户须知" ref="item1">
					<EditorContext name="user_notice" :html="model1.event.user_notice" @changes="detail_content">
					</EditorContext>
				</u-form-item>

				<!-- 				<u-form-item label="用户协议"  ref="item1">
					<EditorContext name="user_agreement" :html="model1.event.user_agreement" @changes="detail_content">
					</EditorContext>
				</u-form-item> -->

				<u-form-item label="活动结束后详情" ref="item1">
					<u--textarea :maxlength="-1" v-model="model1.event.over_content"
						placeholder="请输入活动结束后详情"></u--textarea>
				</u-form-item>

				<u-form-item label="活动结束后照片" ref="item1">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="9"></u-upload>
				</u-form-item>

			</u--form>
		</view>



		<u-button @click="submit" :disabled="submitDisabled"
			customStyle="background-color: #ffd91d">{{ishistory ? '新增' : '修改'}}</u-button>
		<u-picker :show="price_show" :columns="priceList" @cancel="pricecancel" @confirm="priceconfirm"></u-picker>
		<u-picker :show="leader_show" :columns="leaderList" @cancel="leadercancel" @confirm="leaderconfirm"></u-picker>


		<u-datetime-picker :show="apply_starttime_show" v-model="currDate" mode="datetime" closeOnClickOverlay
			@confirm="confirm" @cancel="cancel" @close="close"></u-datetime-picker>

	</view>
</template>

<script>
	import * as Config from '@/utils/config.js'
	import * as EventApi from '@/api/event.js';
	import * as MemberApi from '@/api/member.js';
	import * as groupApi from '@/api/group.js';
	import EditorContext from '@/components/editor/editor.vue'
	export default {
		components: {
			EditorContext: EditorContext
		},
		data() {

			return {
				fileList1: [],
				submitDisabled: false,
				currDate: Number(new Date()),
				apply_starttime_show: false,
				price_show: false,
				leader_show: false,
				member: {},
				model1: {
					event: {
						image1: '',
						remark: '',
					},
					tagList: [],
					grouptagList: []
				},

				rules: {
					'event.theme': {
						type: 'string',
						required: true,
						max: 30,
						message: '请填写活动主题',
						trigger: ['blur', 'change']
					},
					'event.price': {
						type: 'number',
						required: true,
						message: '请填写价钱',
						trigger: ['blur', 'change']
					},
					'event.female_member': {
						type: 'number',
						required: true,
						max: 8,
						min: 1,
						message: '请填写最少女数',
						trigger: ['blur', 'change']
					},
					'event.min_member': {
						type: 'number',
						required: true,
						max: 8,
						min: 1,
						message: '请填写最少成局人数',
						trigger: ['blur', 'change']
					},
					'event.max_member': {
						type: 'number',
						required: true,
						max: 8,
						min: 1,
						message: '请填写最大成局人数',
						trigger: ['blur', 'change']
					},
					'event.apply_starttime': {
						type: 'string',
						required: true,
						message: '请选择报名开始时间',
						trigger: ['blur', 'change']
					},
					'event.apply_endtime': {
						type: 'string',
						required: true,
						message: '请选择报名结束时间',
						trigger: ['blur', 'change']
					},
					'event.starttime': {
						type: 'string',
						required: true,
						message: '请选择活动开始时间',
						trigger: ['blur', 'change']
					},
					'event.endtime': {
						type: 'string',
						required: true,
						message: '请选择活动结束时间',
						trigger: ['blur', 'change']
					},
					'event.address': {
						type: 'string',
						required: true,
						message: '请选择地址',
						trigger: ['blur', 'change']
					},

					tagList: {
						type: 'array',
						min: 1,
						required: true,
						message: '至少选一项',
						trigger: ['change']
					},
				},
				radio: '',
				switchVal: false,
				checkTagList: [],
				group_list: [],
				ishistory: '',

				priceList: [],
				leaderList: [],

				recommendList: [{
						name: '是',
						value: 0,
						disabled: false,
						checked: true
					},
					{
						name: '否',
						value: 1,
						disabled: false,
						checked: false
					},
				],
				statusList: [{
						name: '发布中',
						value: 1,
						disabled: false,
						checked: false
					},
					{
						name: '未发布',
						value: 2,
						disabled: false,
						checked: false
					},
				],
				provider_list: [{
						name: '官方',
						value:'官方',
						disabled: true,
						checked: false
					},
					{
						name: '第三方',
						value: '第三方',
						disabled: false,
						checked: false
					}
				],
				eventStatusList: [{
						name: '组局中',
						value: 0,
						disabled: false,
						checked: false
					},
					{
						name: '成局',
						value: 1,
						disabled: false,
						checked: false
					},
					{
						name: '流局',
						value: 2,
						disabled: false,
						checked: false
					},
				],
			}
		},
		onLoad(e) {
			console.log(e)
			this.getPrices()
			this.getLeaderList()
			this.getMemberInfo()
			this.ishistory = e.ishistory
			if (e.id) {
				this.getDetail(e.id)
			}

		},
		onShow() {

		},
		methods: {
			eventStatusChange(e) {
				this.model1.event.event_status = e.detail.value
			},
			statusChange(e) {
				this.model1.event.status = e.detail.value
			},
			status_provide(e) {
				this.model1.event.provider = e.detail.value
			},
			
			recommendChange(e) {
				this.model1.event.status = e.detail.value
			},

			detail_content(res) {
				this.model1.event[res.name] = res.html
			},

			showDatetimePicker(index) {
				this.current = index
				this.apply_starttime_show = true
			},

			priceclose() {
				this.price_show = false
			},
			priceconfirm(e) {
				this.price_show = false
				let s = e.value[0].split('：');
				this.model1.event.price = Number(s[1])
			},
			pricecancel() {
				this.price_show = false
			},
			getPrices() {
				EventApi.pricemod().then(res => {

					// this.priceList = res.info
					let list = [];
					res.info.forEach(e => {
						list.push(e.name + '：' + e.price)
					})

					this.priceList.push(list)

				})
			},

			getLeaderList() {
				MemberApi.leader_list().then(res => {

					// this.leaderList = res.data
					let list = [];
					res.data.forEach(e => {
						list.push(e.nid + '：' + e.nickname)
					})

					this.leaderList.push(list)

				})
			},
			leaderclose() {
				this.leader_show = false
			},
			leaderconfirm(e) {
				this.leader_show = false
				let s = e.value[0].split('：');
				this.model1.event.employee_id = s[0]
				this.model1.event.leader = s[1]
			},
			leadercancel() {
				this.leader_show = false
			},

			close() {
				this.apply_starttime_show = false
			},
			cancel() {
				this.apply_starttime_show = false
			},
			confirm(e) {
				// this[`show${this.current}`] = false
				this.apply_starttime_show = false
				let arr = ['apply_starttime', 'apply_endtime', 'starttime', 'endtime'];
				this.model1.event[arr[this.current - 1]] = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')

			},

			getMemberInfo() {
				MemberApi.info().then(res => {
					this.member = res.data
					console.log("this.member",this.member)
					 
					//这里已经拿到了是否超级管理员的数据，所以直接在这个函数去处理是否可以开官方局
					if(this.member.super_leader == '是' )
					{
						this.provider_list[0].disabled=false;
						console.log("this.provider_ist",this.provider_list)
						console.log("这里已经拿到了是否超级管理员的数据，所以直接在这个函数去处理是否可以开官方局",this.provider_list)
					}
					else
					{					console.log("this.member.super_leader", this.member.super_leader)
						this.provider_list[0].disabled=true;
						this.provider_list[0].checked=false;
						this.provider_list[1].checked=true;
					}
					
					
				})
			},

			checkboxClick(index) {
				let s = this.model1.event.tag[index].select
				this.model1.event.tag[index].select = s == 0 ? 0 : 1
			},


			birthdayConfirm(e) {
				this.showBirthday = false
				this.model1.event.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				this.$refs.uForm.validateField('event.birthday')
			},

			getDetail(id) {
				let that = this;
				EventApi.event_detail({
					id: id
				}).then(res => {
					this.model1.event = res.info
					this.getTags()
					this.grouplist()
					if(this.model1.event.fileList){
						this.fileList1 = this.model1.event.fileList
					}
					
					this.eventStatusList.forEach(e => {
						if (e.value == res.info.event_status) {
							e.checked = true
						}
					})
					
					console.log("res.info",res.info);

					this.provider_list.forEach(e => {
						if (e.value == res.info.provider) 
						{
							console.log("e.value",e.value);
							console.log("res.info.provider",res.info.provider);
							e.checked = true
						}
					})
					
					this.statusList.forEach(e => {
						if (e.value == res.info.status) {
							e.checked = true
						}
					})

					this.recommendList.forEach(e => {
						if (e.value == res.info.recommend) {
							e.checked = true
						}
					})

				})
			},


			//获取所有的团体
			grouplist() {
				console.log("grouplist")
				uni.request({
					url: Config.baseUrl + '/api/miniapp/group/get_group_list.php',
					data: {
						page: this.page,
						Authorization: Config.getStorageUserId(),
					},
					success: (res) => {
						this.group_list = res.data.info
						console.log("this.group_list", this.group_list)
						
						
					    let list = this.model1.event.group_nid.split(',')
						console.log("this.model1.event.group_nid", this.model1.event)
						console.log("list", list)
						
						list.forEach(e => {
							let b = this.model1.event.group_nid ? this.model1.event.group_nid.includes(e) : false
							// this.group_list.push({
							// 	name: e,
							// 	checked: b
							// })
							if (b) {
								this.model1.grouptagList.push(e)
							}
						
						})
						
						
					}
				});
			
				
			},
			
			

			getTags() {
				EventApi.event_author().then(res => {
					let list = res.data.event_author.split(',')

					list.forEach(e => {
						let b = this.model1.event.tag ? this.model1.event.tag.includes(e) : false
						this.checkTagList.push({
							name: e,
							checked: b
						})
						if (b) {
							this.model1.tagList.push(e)
						}

					})

				})
			},

			chooseLocation() {
				console.log('详细地址')
				let self = this;
				uni.chooseLocation({
					success: (res) => {
						self.model1.event.address = res.address;
						self.model1.event.location = res.latitude + ',' + res.longitude;
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					},
					fail: () => {
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						self.model1.detail = '详细地址'
						uni.getSetting({
							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success: (data) => {
														// 如果用户授权了地理信息在，则提示授权成功
														if (data
															.authSetting[
																'scope.userLocation'
															] === true
														) {
															uni.showToast({
																title: "授权成功",
																icon: "success",
																duration: 1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (
																	res
																) => {
																	self.model1
																		.event
																		.address =
																		res
																		.address;
																	self.model1
																		.event
																		.location =
																		res
																		.latitude +
																		',' +
																		res
																		.longitude;
																	console
																		.log(
																			'位置名称：' +
																			res
																			.name
																		);
																	console
																		.log(
																			'详细地址：' +
																			res
																			.address
																		);
																	console
																		.log(
																			'纬度：' +
																			res
																			.latitude
																		);
																	console
																		.log(
																			'经度：' +
																			res
																			.longitude
																		);
																}
															})
														} else {
															uni.showToast({
																title: "授权失败",
																icon: "none",
																duration: 1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			},

			submit() {
				// this.model1.event.fileList = this.fileList1
				// console.log(this.model1.event)
				// return false;
				if (!this.model1.event.image1) {
					uni.$u.toast('请上传封面')
					return false
				}
				this.$refs.uForm.validate().then(res => {


	               let group = "";
					this.model1.grouptagList.forEach(e => {
						console.log("e",e)
						group += e + ','
					})
					
					this.model1.event.grouptag = group.substr(0, group.length - 1)
					
					console.log("this.model1.event",this.model1.event)
					
					
					let tag = "";
					this.model1.tagList.forEach(e => {
						tag += e + ','
					})

					this.model1.event.tag = tag.substr(0, tag.length - 1)
					this.model1.event.fileList = JSON.stringify(this.fileList1)
					
					// if(!this.model1.event.provider)
					// {
					// 	this.model1.event.provider = "第三方"
					// }

					this.submitDisabled = true;




					if (this.ishistory) {
						EventApi.add(this.model1.event).then(res => {
							uni.$u.toast(res.info)
							if (res.status == 200) {

								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/activity/manage'
									})
								}, 1000)

							} else {
								this.submitDisabled = false
							}

						})
					} else {
						EventApi.update(this.model1.event).then(res => {
							uni.$u.toast(res.info)
							if (res.status == 200) {

								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/activity/manage'
									})
								}, 1000)

							} else {
								this.submitDisabled = false
							}

						})
					}


				}).catch(errors => {
					//	uni.$u.toast('校验失败')

				})
			},

			// 删除图片
			deletePic(event) {
				
				
				EventApi.delete_event_file({url: this.fileList1[event.index].url}).then(res => {
				
					if(res.status == 200){
						this[`fileList${event.name}`].splice(event.index, 1)
					}else{
						uni.$u.toast(res.info)
					}
				
				})

			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						header: {
							Authorization: Config.getStorageUserId(),
						},
						url: Config.baseUrl +
							'/api/miniapp/event.php?act=upload_img',
						filePath: url,
						name: 'file',
						success: (res) => {
							setTimeout(() => {
								let d = JSON.parse(res.data)
								if (d.status == 200) {
									resolve(d.url)
								} else {
									uni.$u.toast('上传失败')
								}

							}, 1000)
						}
					});
				})
			},


			upload() {
				let that = this;
				uni.chooseImage({
					success: (chooseImageRes) => {

						uni.uploadFile({
							header: {
								Authorization: Config.getStorageUserId(),
							},
							url: Config.baseUrl +
								'/api/miniapp/event.php?act=upload_img',
							filePath: chooseImageRes.tempFilePaths[0],
							name: 'file',
							success: (uploadFileRes) => {
								let d = JSON.parse(uploadFileRes.data)
								if (d.status == 200) {
									that.model1.event.image1 = d.url
								} else {
									uni.$u.toast('上传失败')
								}
							}
						});
					}
				});
			},

		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	}
</script>

<style scoped lang="scss">
	.page {
		.mr-20 {
			margin-right: 20rpx;
		}

		.banner {
			width: 750rpx;
			height: 280rpx;
		}

		.form {
			padding: 20rpx;
		}

		.avatar-btn {
			width: 200rpx;
			margin: auto;
		}

		.tag {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			margin-top: 20rpx;

			.tag-item {
				margin-bottom: 20rpx;
			}
		}

		.submit {
			background-color: #ffd91d;
		}
	}
</style>